package com.mrdeer.web.controller.app;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mrdeer.common.JSONResult;
import com.mrdeer.common.entity.bo.MiniLoginBO;
import com.mrdeer.common.entity.sys.User;
import com.mrdeer.security.SecurityUtil;
import com.mrdeer.web.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;


/**
 * 小程序登录授权
 *
 * @author xiejianchu
 * @email 657572667@qq.com
 * @date 2020-11-22 12:37:21
 */
@Slf4j
@RestController
@RequestMapping("/mini")
@Api(value = "小程序登录接口", tags = "小程序登录接口")
public class MiniAppUserController {

    @Resource
    private SysUserService userService;

    @Resource
    private SecurityUtil securityUtil;

    @Value("${miniapp.app-id}")
    private String appId;

    @Value("${miniapp.app-secret}")
    private String appSecret;

    @Value("${mrdeer.token.tokenExpireTime}")
    private Long tokenExpireTime;

    @PostMapping("login")
    @ApiOperation("登录")
    public JSONResult login(@RequestBody MiniLoginBO miniLoginBO) {

        //1.获取微信登录的openID
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", miniLoginBO.getCode());
        map.put("grant_type", "authorization_code");

        String response = HttpUtil.post(url, map);
        log.info("response:" + response);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");

        if (openId == null || openId.length() == 0) {
            return JSONResult.errorMsg("获取openId失败");
        }
        User userEntity = new User();
        userEntity.setOpenId(openId);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenId, openId);
        int count = userService.count(queryWrapper);
        if (count == 0) {
            //需要注册之后在进行登录
            userEntity.setId(Sid.next());
            userEntity.setNickname(miniLoginBO.getNickname());
            userEntity.setUsername(miniLoginBO.getNickname());
            userEntity.setAvatar(miniLoginBO.getPhoto());
            userEntity.setType(2);  //2:微信账号
            userEntity.setCreateTime(new Date());
            userEntity.setUpdateTime(new Date());
            userService.save(userEntity);
        }

        userEntity = userService.getOne(queryWrapper);
        //登录
        String token = securityUtil.getToken(userEntity.getUsername(), true);
        HashMap resultMap = new HashMap();
        resultMap.put("token", openId);
        resultMap.put("expire", tokenExpireTime);
        return JSONResult.ok(resultMap);
    }

}
